<template>
    <div>
        <div class="boxWrapper tabbox">
            <el-tabs v-model="currentName">
                <el-tab-pane label="菜单管理" name="1">
                        <span slot="label"><i class="iconfont">&#xe687;</i> 菜单管理</span>
                </el-tab-pane>
                <el-tab-pane label="测点管理" name="2">
                        <span slot="label"><i class="iconfont">&#xe6f4;</i> 测点管理</span>
                </el-tab-pane>
            </el-tabs>
        </div>
        <div class="monitor-wrapper" v-show="currentName == 1">
            <cardBox class="colum" title="选择导航">
                <template #right>
                   <div>
                        <el-tooltip class="item" effect="dark" content="新增导航方式" placement="top-start">
                        <el-button size="small" type="primary" class="typesBtn" icon="el-icon-plus" @click="treeAddEdit('add')" v-if="permissions.showRoleAdd"></el-button>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="编辑导航方式" placement="top-start">
                        <el-button size="small" type="success" class="typesBtn" icon="el-icon-edit" @click="treeAddEdit('edit')" v-if="permissions.showRoleEdit"></el-button>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="删除导航方式" placement="top-start">
                        <el-button size="small" type="danger" class="typesBtn" icon="el-icon-delete" @click="treeAddEdit('del')" v-if="permissions.showRoleDel"></el-button>
                        </el-tooltip>
                    </div>
                </template>
                <div class="inupt-style">
                    <el-select size="small" @change="treeChange" v-model="treeModelName" placeholder="选择导航方式" style="width:100%">
                        <el-option
                        v-for="item in treeOptions"
                        :key="item.navigationID"
                        :label="item.navigationName"
                        :value="item.navigationName">
                        </el-option>
                    </el-select>
                </div>
                <div>
                    <treeMenu :treeData="treeList" name="lable" class="tree-wrapper" @menuLeftClick="handleMenuClick"
                    isRightMenu ref="treeMenu" @addMenuItem="handleAddMenu" @delMenuItem="handleDelTreeMenu" 
                    @editMenuItem="handleAddMenu"
                    :showRoleAdd="permissions.showRoleAdd"
                    :showRoleEdit="permissions.showRoleEdit"
                    :showRoleDel="permissions.showRoleDel"
                    />
                </div>
            </cardBox>
            <cardBox class="colum" title="关联仪器">
                <template #right>
                    <el-button type="danger" size="mini" icon="el-icon-delete" :disabled="treeSelection.length <= 0"  @click="handleRemovePoint" v-if="permissions.showRoleDel">移除</el-button>
                </template>
                <el-table :data="pointsList"  height="calc(100vh - 260px)"
                    @selection-change="treeHsChange" border style="border-top:0px;">
                    <el-table-column  type="selection" width="45" align="center"></el-table-column>
                    <el-table-column align="center" label="编号" type="index"  width="60" />
                    <el-table-column  prop="treeName"  label="仪器名称" align="center"></el-table-column>
                </el-table>
            </cardBox>
           <cardBox class="colum" title="测点类型">
            <div class="inupt-style">
                    <el-input v-model="searchName" placeholder="关键字查询" size="small" style="width:100%"  @keyup.enter.native="getTypeDataList"/>
                </div>
                <el-table
                    height="calc(100vh - 320px)" border
                    ref="mytable"
                    :data="typeData"
                    @row-click="handleRowClick"
                    highlight-current-row >
                    <el-table-column align="center" label="编号" type="index" width="60"/>
                    <el-table-column  prop="instR_Name" label="类型" align="center"></el-table-column>
                </el-table>
           </cardBox>
                
            <cardBox class="colum" title="测点列表">
                <template #right>
                    <el-button type="primary" size="mini" 
              :disabled="pointSelection.length <= 0" @click="handleUsePoint" icon="el-icon-circle-check" v-if="permissions.showRoleEdit">使用</el-button>
                </template>
                <div class="inupt-style">
                    <el-input v-model="pointSearch" placeholder="关键字查询" size="small" style="width:100%"  @keyup.enter.native="getPointsList"/>
                </div>
                <el-table  :data="powerpointList" ref="multipleTable" @selection-change="pointHsChange"  
                height="calc(100vh - 320px)">
                <el-table-column type="selection" width="45" align="center"></el-table-column>
                <el-table-column align="center" label="编号" type="index" width="50" />
                <el-table-column prop="pointName" label="测点名称" align="center"></el-table-column>
                <el-table-column  prop="workStatus" label="状态" align="center"/>
                </el-table>
            </cardBox>
        </div>

        <pointManage v-if="currentName == 2" :stationId="stationId" :showRoleAdd="permissions.showRoleAdd" :showRoleEdit="permissions.showRoleEdit" :showRoleDel="permissions.showRoleDel"/>

        <el-dialog title="设置菜单" :visible.sync="dialogMenuVisible" width="450px" :before-close="handleCancelDialog" v-dialogDrag>
            <el-form :model="menuForm" label-width="100px" ref="menuForm" :rules="menuRules">
                <el-form-item label="菜单名称" required prop="treeName">
                    <el-input v-model="menuForm.treeName" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="类型" prop="productTypeID">
                <el-radio-group v-model="menuForm.productTypeID">
                    <el-radio :label="5">环境量</el-radio>
                    <el-radio :label="7">斜测仪</el-radio>
                    <el-radio :label="0">其它仪器</el-radio>
                </el-radio-group>
                </el-form-item>
            </el-form>
            <div class="btnGroup">
                <el-button @click="handleCancelDialog" size="small" icon="el-icon-circle-close">取 消</el-button>
                <el-button type="primary" @click="handleAddMenuSave" size="small" icon="el-icon-circle-check">保存</el-button>
            </div>
        </el-dialog>

        <el-dialog :title="treeAddEditTitle" :visible.sync="treeAddEditDialogVisible" v-dialogDrag  width="450px">
            <el-form ref="treeForm" :model="treeTypeForm" label-width="100px">
                <el-form-item label="导航名称">
                <el-input size="medium" class="searchIpt" v-model="treeTypeForm.navigationName" placeholder="请输入"/>
                </el-form-item>
                <el-form-item label="启用导航">
                <el-switch
                    v-model="treeTypeForm.state"
                    active-color="#13ce66"
                    inactive-color="#f0f0f0"
                    :active-value="1"
                    :inactive-value="0"
                    >
                </el-switch>
                </el-form-item>
            </el-form>
            <div class="btnGroup">
                <el-button @click="treeAddEditDialogVisible = false" size="small" icon="el-icon-circle-close">取消</el-button>
                <el-button type="primary" icon="el-icon-circle-check" @click="handleSaveModelType" size="small">保存</el-button>
            </div>
        </el-dialog>
    </div> 
</template>
<script>
import bus from '@/utils/eventBus.js';
import treeMenu from '@/components/base/treeMenu.vue'
import {GetAllPowerNavigationBYid,GetTreeAsyncSet,GetPointsByTreeId,EditTree,AddTree,DelTree,RemoveTreePoints,GetPowerPointType,QueryPointByName,AddTreePoints,DelPowerNavigation,AddPowerNavigation,EditPowerNavigation} from '@/api/https'
import cardBox from "@/components/base/cardBox.vue";
import pointManage from '@/components/page/setting/pointManage.vue';
import permissionMixin from '@/utils/permission.js'
export default ({
    name:'monitorData',
    mixins: [permissionMixin],
    components:{treeMenu,pointManage,cardBox},  
    data() {
      return {
        currentName:'1',
        stationId:sessionStorage.getItem("stationId"),
        treeModelName:'',
        treeOptions:[],
        treeList:[],
        treeid:0,
        pointsList:[],
        treeDataEdit:false,
        treeNodeLevel:'',
        menuForm:{},
        dialogMenuVisible:false,
        menuRules:{
            treeName:[{ required: true, message: '请输入名称'}],
            productTypeID:[{ required: true, message: '请选择类型'}]
        },
        treeSelection:[],
        typeData:[],
        searchName:'',
        instR_ID:'',
        productTypeID:'',
        pointSearch:'',
        powerpointList:[],
        pointSelection:[],
        treeAddEditTitle:'',
        treeAddEditDialogVisible:false,
        treeTypeForm:{}
      }  
    },
    mounted(){
        this.initBasin()
        this.getTreeTypeList()
        this.getTypeDataList()
    },
    computed: {
        permissions() {
            return this.getPermissions() || {}
        }
    },
    activated(){
       this.initBasin()
        const newStationId = sessionStorage.getItem("stationId");
        if (this.stationId != newStationId) {
            this.stationId = newStationId
            this.clearData()
            this.getTreeTypeList()
            this.getTypeDataList()
        }
    },
    deactivated(){
        bus.$off('station-changed', this.handleStationChanged);
    },
    beforeDestroy(){
        bus.$off('station-changed', this.handleStationChanged);
        this.clearData()
    },
    methods:{
        initBasin() {
            bus.$emit('showBasin', true);
            bus.$off('station-changed', this.handleStationChanged);
            bus.$on('station-changed', this.handleStationChanged);
        },
        handleStationChanged(newStationId, targetRoute) {
            if (!targetRoute || targetRoute === this.$route.name) {
                this.stationId = newStationId;
                this.clearData()
                this.getTreeTypeList()
                this.getTypeDataList()
            }
        },
        getTreeTypeList() {
            GetAllPowerNavigationBYid({
                station_id:this.stationId
            }).then(res=>{
                if (res.isSuccess && res.data && res.data.length > 0) {
                    this.treeOptions = res.data;
                    this.treeModelName = this.treeOptions[0].navigationName;
                    this.getTreeData()
                }else{
                    this.clearData()
                }
            });
        },
        clearData(){
            this.treeList = []
            this.treeOptions = []
            this.treeModelName = ''
            this.treeid = 0
            this.pointSearch = ''
            this.searchName = ''
            this.treeSelection = []
            this.pointSelection = []
            this.typeData = []
            this.powerpointList = []
            this.pointsList = []
        },
        getTreeData() {
            // 树状导航
            GetTreeAsyncSet(this.stationId,this.treeModelName).then(res=>{
                if(res.isSuccess && res.data && res.data.length > 0){
                    this.treeList = res.data;
                }else{
                    this.treeList = []
                }
            })
        },
        handleMenuClick(data){
            if ((data.treeName != '' && !data.children) || data.ifEnvironment == 1) {
                this.treeid = data.treeid;
                this.getPointsType(data.treeid);
            }else{
                this.treeid = data.treeid || 0
            }
        },
        getPointsType(){
            // 关联仪器
            GetPointsByTreeId(this.treeid,this.stationId,this.treeModelName).then(res=>{
                if(res.isSuccess){
                    this.pointsList = res.data || [];
                }else{

                }
            })
        },
        handleAddMenu(data,isEdit,treeNodeLevel){
            this.treeDataEdit = isEdit
            this.treeNodeLevel = treeNodeLevel || ''
            if(isEdit){
                const _editData = Object.assign({},data.node)
                this.menuForm = {..._editData}
            }else{
                if(data){
                    this.menuForm = {
                        id: 0,
                        treeid:0,
                        statioN_ID:this.stationId,
                        treeName:'',
                        upTreeID: treeNodeLevel == 1 ? data.node.upTreeID || '' : data.node.treeid || '',
                        isBottom:data.node.isBottom || false,
                        codE_ID:data.node.codE_ID || '',
                        treeStyle:this.treeModelName || '',
                        productTypeID:0
                    }
                }else{
                    this.menuForm = {
                        id: 0,
                        treeid:0,
                        statioN_ID:this.stationId,
                        treeName:'',
                        upTreeID: '',
                        isBottom:false,
                        codE_ID:'',
                        treeStyle:this.treeModel || '',
                        productTypeID:0
                    }
                }
                
            }
            this.dialogMenuVisible = true
        },
        handleCancelDialog(){
            this.dialogMenuVisible = false
            this.menuForm = {}
            this.treeDataEdit = false
            this.treeNodeLevel = ''
        },
        handleAddMenuSave(){
            this.$refs['menuForm'].validate((valid) => {
                if (valid) {
                    if(this.treeDataEdit){
                        EditTree(this.menuForm).then(res=>{  
                            if(res.isSuccess){
                                this.handleCancelDialog()
                                this.getTreeData();
                            }else{
                                this.$message.error(res.errorMessage)
                            }
                        })
                    }else{
                        AddTree(this.menuForm).then(res=>{  
                            if(res.isSuccess){
                                this.handleCancelDialog()
                                this.getTreeData();
                            }else{
                                this.$message.error(res.errorMessage)
                            }
                        })
                        
                    }
                } else {
                    return false;
                }
            });
        },
        handleDelTreeMenu(data){
            this.$confirm(`确认删除名称为 ${data.lable} 的节点？`,'提示',{
                type:'warning'
            }).then(() => {
                DelTree(data.id).then(res=>{  
                    if(res.isSuccess){
                        this.getTreeData();
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }).catch(() => {});  
        },
        treeHsChange(val) {
            if(val.length > 0){
                const list = []
                val.forEach(item=>{
                    list.push(item.codE_ID)
                })
                this.treeSelection = list
            }else{
                this.treeSelection = []
            }
        },
        handleRemovePoint(){
            if (this.treeSelection.length > 0) {
                let _data = {
                    treeid: this.treeid,
                    p_id: this.treeSelection,
                    statioN_ID: this.stationId,
                    style: this.treeModelName
                }
                this.$confirm(`您本次选择了${this.treeSelection.length}条数据，确认要全部移除？`,'提示',{
                    type:'warning'
                }).then(() => {
                    RemoveTreePoints(_data).then(res=>{
                        if(res.isSuccess){
                            this.$message.success("移除成功");
                            this.getPointsType();
                            this.treeSelection = [];
                        }else{
                            this.$message.error(res.errorMessage);
                        }
                    })
                }).catch(() => {});  
            }
        },
        getTypeDataList() {
            GetPowerPointType(this.searchName,this.stationId,1,100).then(res=>{
                if (res.isSuccess) {            
                    this.typeData = res.data.data || []
                }
            });
        },
        handleRowClick(rowData) {
            this.instR_ID = rowData.instR_ID;
            this.productTypeID = rowData.productTypeID
            this.getPointsList()
        },
        getPointsList() {
            QueryPointByName({
                INSTR_ID:this.instR_ID,
                name:this.pointSearch,
                ProductTypeID:this.productTypeID
            }).then(res=>{
                if (res.isSuccess) {
                    this.powerpointList = res.data || [];
                    if(this.powerpointList.length > 0){
                        this.powerpointList.forEach(item => {
                            const matched = this.typeData.find(({codE_ID}) => codE_ID === item.id);
                            if (matched) {
                                Object.assign(item, { workStatus: '已使用' });
                            } else {
                                Object.assign(item, { workStatus: '未使用' });
                            }
                        })
                    }
                }
            });
        },
        handleUsePoint() {
            if (this.pointSelection.length > 0) {
                let _data = {
                    treeid: this.treeid,
                    p_id: this.pointSelection,
                    statioN_ID: this.stationId,
                    style: this.treeModelName
                }
                this.$confirm(`您本次选择了${this.pointSelection.length}条数据，确认要全部改为使用？`,'提示',{
                    type:'warning'
                }).then(() => {
                    AddTreePoints(_data).then(res=>{
                        if(res.isSuccess){
                            this.$message.success("操作成功");
                            this.pointSearch = ''
                            this.pointSelection = [];
                        }else{
                            this.$message.error(res.errorMessage);
                        }
                    })
                }).catch(() => {});       
            }
        },
        pointHsChange(val) {
            if(val.length > 0){
                const list = []
                val.forEach(item=>{
                    list.push(item.id)
                })
                this.pointSelection = list;
            }else{
                this.pointSelection = []
            }
        },
        treeAddEdit(type) {
            if (type == 'add') {
                this.treeAddEditTitle = '新增导航';
                this.treeAddEditDialogVisible = true;
            } else if (type == 'edit') {
                this.treeAddEditTitle = '编辑导航';
                this.treeAddEditDialogVisible = true;
            } else {
                this.$confirm(`确认删除名称为 ${this.treeModelName} 的导航方式？`, '提示',{type: "warning"}).then(() => {
                    let id = ''
                    this.treeOptions.forEach(item=>{
                        if(item.navigationName == this.treeModelName){
                            id = item.navigationID
                        }
                    })
                    DelPowerNavigation(id).then(res=>{
                        if (res.isSuccess) {
                            this.$message.success("删除成功");
                            this.getTreeTypeList();
                        }
                    });
                }).catch(() => {});  
            }
        },
        handleSaveModelType() {
            const _data = {
                ...this.treeTypeForm,
                station_id:this.stationId
            }
            if (this.treeAddEditTitle == '新增导航') {
                AddPowerNavigation(_data).then(res=>{
                    if (res.isSuccess) {
                        this.$message.success("新增成功");
                        this.getTreeTypeList();
                        this.treeAddEditDialogVisible = false;
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                });
            } else {
                EditPowerNavigation(_data).then(res=>{
                    if (res.isSuccess) {
                        this.$message.success("编辑成功");
                        this.getTreeTypeList();
                        this.treeAddEditDialogVisible = false;
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                });
            }
        },
        treeChange(){
            this.pointsList = []
            this.getTreeData()
        }
    }
})
</script>
<style scoped lang="scss">
.monitor-wrapper{
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 10px; 
    .colum{
        height: calc(100vh - 180px) ;
        margin-top:10px;
    }
    
}
.inupt-style{
    width:90%;
    margin:10px auto;
}
.tree-wrapper{
    height: calc(100vh - 290px);
    overflow: auto;
}
.typesBtn {
  padding: 5px;
  margin: 0 4px !important;
  border:none !important;
}
</style>
